package com.aurora.CETManagementSystem.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.Base64;
import java.util.Base64.Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ResultInquiryUtils {

    public static final String C = "CET";

    public static final String IMG_URL = "http://cet.neea.edu.cn/imgs/";

    public static final String QUERY_URL = "http://cache.neea.edu.cn/cet/query";

    public static final String REFERER = "http://cet.neea.edu.cn/cet";

    /**
     * 获取验证码
     *
     * @param ik       准考证号
     * @param response 响应头
     *                 return 图片的Base64编码
     */
    public static String getVerificationCode(String ik, HttpServletResponse response) {
        if (StringUtils.isBlank(ik)) {
            throw new NullPointerException("准考证号不能为null或为空。");
        }
        if (null == response) {
            throw new NullPointerException("响应头不能为null。");
        }
        String imageToBase64 = "";
        String url = "http://cache.neea.edu.cn/Imgs.do?c=" + C + "&ik=" + ik;
        // 获得一个httpclient对象
        HttpGet httpget = new HttpGet(url);
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        // 设置请求头
        httpget.addHeader("Referer", REFERER);
        CloseableHttpResponse getResponse = null;
        String cookie = "";
        try {
            getResponse = httpclient.execute(httpget);
            if (getResponse.getStatusLine().getStatusCode() == 200) {
                String resultString = EntityUtils.toString(getResponse.getEntity(), "UTF-8");
                // 取到括号里面的图片名称
                String substr = resultString.substring(13, resultString.length() - 3);
                String img_url = IMG_URL + substr + ".png";
                imageToBase64 = NetImageToBase64(img_url);
                // 获取cookies信息
                Header[] headers = getResponse.getHeaders("Set-Cookie");
                String[] split = headers[0].getValue().split(";");
                cookie = split[0];
            }
            response.setHeader("Eng-Cookie", cookie);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            if (getResponse != null) {
                try {
                    getResponse.close();
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
        return imageToBase64;
    }

    /**
     * 网络图片转换Base64的方法
     *
     * @param netImagePath
     */
    private static String NetImageToBase64(String netImagePath) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        Encoder encoder = Base64.getEncoder();

        return encoder.encodeToString(data.toByteArray());
    }

    /**
     * 获取考试成绩
     *
     * @param ticketNumber     准考证号
     * @param name             姓名
     * @param verificationCode 验证码
     * @param request          请求头
     * @return
     * @throws UnsupportedEncodingException
     */
    public static Map<String, Object> resultInquiry(String ticketNumber, String name, String verificationCode,
                                                    HttpServletRequest request) {
        if (StringUtils.isBlank(ticketNumber) || StringUtils.isBlank(name)
                || StringUtils.isBlank(verificationCode) || null == request) {
            throw new NullPointerException("参数错误。");
        }
        String cookie = request.getHeader("Eng-Cookie");
        //if (StringUtils.isBlank(cookie)) {
        //    throw new NullPointerException("Eng-Cookie未传。");
        //}
        Map<String, Object> map = new HashMap<>();

        // 获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String idCode = idCode(ticketNumber);
        String data = idCode + "," + ticketNumber + "," + name;
        // 拼接url
        String url = QUERY_URL + "?data=" + data + "&v=" + verificationCode;
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        httpGet.addHeader("Referer", REFERER);
        httpGet.addHeader("Cookie", cookie);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                // 正则表达式，用于匹配()里面的文字
                String skh = "(?<=\\()[^\\)]+";
                Pattern pattern = Pattern.compile(skh);
                Matcher matcher = pattern.matcher(resultString);
                boolean is = matcher.find();
                if (is) {
                    // 把Json数据转为map
                    map = JSONObject.parseObject(matcher.group());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new InternalError(e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
        return map;
    }

    /**
     * 通过准考证号获取data值的前缀
     *
     * @param ticketNumber 准考证号
     * @return
     */
    private static String idCode(String ticketNumber) {
        String substring = ticketNumber.substring(9, 10);
        // todo 这个前缀可能每年会变
        if ("1".equals(substring)) {
            return "CET4_192_DANGCI";
        } else {
            return "CET6_192_DANGCI";
        }
    }
}
